from random import randint

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView

import constants

from  django_redis import get_redis_connection

from libs.captcha.captcha import captcha
import logging

from libs.yuntongxun.sms import CCP
from verifications.serializers import SmscodesViewSerializers

logger = logging.getLogger('meiduo')


class SmscodesView(GenericAPIView):
    """
    发送短信验证
    GET /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx&image_code_id=xxxx

    """

    # 序列化器
    serializer_class = SmscodesViewSerializers

    # 获取参数
    def get(self, request, mobile):
        # 获取参数
        data = request.query_params
        # 反序列化
        serialize = self.get_serializer(data=data)
        # 校验
        serialize.is_valid(raise_exception=True)
        # 生成短信内容
        smscode = '%06d' % randint(0, 999999)
        # 讲短信验证码保存在redis中
        redis_conn = get_redis_connection('code')
        # 判断是否频繁发送短信
        if redis_conn.get('sms_flag_%s' % mobile):
            return Response(status=status.HTTP_429_TOO_MANY_REQUESTS)

        redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, smscode)
        redis_conn.setex('sms_flag_%s' % mobile, 60, 1)

        from celery_tasks.sms.tasks import send_sms_code
        # 调用第三方 发送短信
        send_sms_code.delay(mobile, smscode)
        # 返回响应
        return Response({'message': 'ok'})


class RegisterImageCodeView(APIView):
    """
    生成图片验证码

    """

    def get(self, request, image_code_id):
        """
        1.使用第三方工具 生成图片验证码
        2.将生成的图片验证码内容保存在redis中
        3.将图片内容返回到页面中，修改请求头
        :param request:
        :param image_code_id:
        :return:
        """
        # 使用第三方工具生成图片验证码
        text, img = captcha.generate_captcha()

        # 生成到redis中
        try:
            # 获取redis连接
            redis_con = get_redis_connection('code')
            # 保存图片验证码
            redis_con.setex('img_%s' % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        except Exception as e:
            logger.error(e)
        # 返回响应 修改content_type
        return HttpResponse(img, content_type='image/jpeg')
